#include "Sock.hpp"
#include <fstream>
#include <sys/stat.h>

#define WWWROOT "./wwwroot/"
#define HOME_PAGE "index.html"

void Usage(std::string args)
{
    std::cout << "Usage : " << args << " server_port" << std::endl;
}

void *handler(void *args)
{
    pthread_detach(pthread_self());

    int sock = *(int *)args;
    delete (int *)args;

#define NUM 1024 * 10
    char buf[NUM];
    memset(buf, 0, sizeof(NUM));

    ssize_t sz = recv(sock, buf, sizeof(buf) - 1, 0);
    if (sz > 0)
    {
        buf[sz] = 0;
        std::cout << buf << std::endl;

        std::string fileloc = WWWROOT;
        fileloc += HOME_PAGE;
        // fileloc += "a/b";
        std::ifstream ifs(fileloc);

        if (!ifs.is_open())
        {
            std::string http_response = "HTTP/1.0 404 NotFount";
            http_response += "Content-Type: text/html, charset=utf-8";
            http_response += "\n";
            http_response += "<html><p> 你访问的资源不存在 </p></html>";

            send(sock, http_response.c_str(), http_response.size(), 0);
        }
        else
        {
            std::string line;
            std::string echo;

            while (std::getline(ifs, line))
            {
                echo += line;
            }

            struct stat fst;
            stat(fileloc.c_str(), &fst);

            std::string http_response = "HTTP/1.0 200 OK\n";
            // std::string http_response = "HTTP/1.0 404 NotFount";
            // std::string http_response = "HTTP/1.0 302 Temporarily Move\n";
            // http_response += "Location: http://www.bilibili.com";

            http_response += "Set-Cookie: id=1111\n";
            http_response += "Set-Cookie: password=2222\n";
            http_response += "Content-Type: text/html, charset=utf-8\n";
            http_response += "Content-Length: ";
            http_response += std::to_string(fst.st_size);
            http_response += "\n\n";
            http_response += echo;
            // http_response += "\n";
            http_response += "\n";

            // std::string http_response = "HTTP/1.0 200 OK\n";
            // http_response += "Content-Type: text/plain\n";
            // http_response += "\n";
            // http_response += "hello, i'm from the futurn\n";

            send(sock, http_response.c_str(), http_response.size(), 0);
        }
    }
    close(sock);
    return nullptr;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(-1);
    }
    int sock = Sock::Socket();

    Sock::Bind(sock, atoi(argv[1]));
    Sock::Listen(sock);

    while (true)
    {
        pthread_t tid;
        int new_sock = Sock::Accept(sock);
        int *psock = new int(new_sock);

        pthread_create(&tid, nullptr, handler, psock);
    }

    return 0;
}